import {createRouter, createWebHashHistory, createWebHistory} from "vue-router";
import NProgress from '@/config/nprogress'
import type {RouteRecordRaw} from 'vue-router'
import {userStore} from "@/store/modules/user";
import {menuStore} from '@/store/modules/menu'


export const routes: RouteRecordRaw[] = [
	// @ts-ignore
	{
		path: '',
		component: () => import('@/layout/index.vue'),
		name: 'AppMain',
		redirect: '/home',
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login/index.vue'),
		meta: {
			title: "登录",
		}
	},
	{
		path: '/:pathMatch(.*)*',
		name: "404",
		component: () => import("@/views/errorPage/404.vue"),
		meta: {
			title: "404页面"
		}
	},
]

const router = createRouter({
	history: createWebHistory(),
	routes,
	strict: true,
	scrollBehavior: () => ({left: 0,top: 0}),
})

router.beforeEach(async (to,from) => {
	NProgress.start()
	const user = userStore()
	const menu = menuStore()
	if (user.token){
		if (to.path === '/login') {
			return from.path
		} else {
			if (!menu.menuList.length){
				await menu.setMenuList()
				return to.path
			}
		}
	}else {
		if (to.path !== '/login'){
			return '/login'
		}
	}
})

router.afterEach(() => {
	NProgress.done();
})


export default router

